from django.shortcuts import render, HttpResponse,reverse
from web.forms.file import FileFildeForm
from django.http import JsonResponse
from web.forms.project import S28
from django.http import JsonResponse
from scripts.cos_upload_demo import delete_file, cos_credentialss
from sts.sts import Sts
from django.views.decorators.csrf import csrf_exempt
import json



def file(request, project_id):
    """get请求 返回页面 POSt请求 添加文件夹"""
    # /namge/file
    # namage/ file/?forder_id=5
    father = None  # 定义一个变量 判断father值
    foder_id = request.GET.get('folder', '')  # 获取url参数 默认值为空字符串
    if foder_id:
        if foder_id.isdecimal():  # 如果是10进制的数字
            ret_tuple = S28().search('file_repository', {'id': foder_id, 'type': '1'})  # 数据库查询url参数对应的数据信息
            if len(ret_tuple) != 0:  # 如果查询到了 给father赋值
                father = ret_tuple[0][0]

    if request.method == 'GET':
        breadcrumb_list = []
        if foder_id != '':
            parent = S28().search('file_repository', {'id': foder_id, 'type': '1'})
            while len(parent) != 0:
                breadcrumb_list.insert(0, {'id': parent[0][0], 'name': parent[0][2]})
                parent = S28().search('file_repository', {'id': parent[0][5], 'type': '1'})
        form = FileFildeForm(request=request, father=father)
        if father == None:
            father = 0
            file_repository = S28().search('file_repository', {'father': '0'})
        else:
            file_repository = S28().search('file_repository', {'father': father})
        return render(request, 'file.html', {'form': form, 'file_repository': file_repository, 'breadcrumb_list': breadcrumb_list, 'father': father})
    fid = request.POST.get('fid', '')
    if fid != '':
        if fid.isdecimal():
            edit_tuple = S28().search('file_repository', {'id': str(fid), 'type': '1', 'project_id': request.obj[0][0]})
            if len(edit_tuple) != 0:
                name = request.POST.get('file_name')

                S28().upload('file_repository', {'name': name}, {'id': str(fid), 'type': '1', 'project_id': request.obj[0][0]})
                return JsonResponse({'status': True})
        else:
            pass

    form = FileFildeForm(data=request.POST, request=request, father=father)  # 传参数 request 和father值
    if form.is_valid():  # 验证通过
        name = form.cleaned_data.get('file_name')
        if father == None:  # 没有url值 或者url的值是一个随便输入的 father值就是0 name就直接存在根目录 否则就根据father的录入
            S28().insert_into('file_repository', {'name': name, 'type': '1', 'father': '0', 'project_id': project_id})
        else:
            S28().insert_into('file_repository', {'name': name, 'type': '1', 'father': father, 'project_id': project_id})
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def file_delete(request, project_id):
    """删除文件"""
    fid = request.GET.get('fid')
    father_list = []
    father_id = S28().search('file_repository', {'id': fid})  # [((),),]
    for i in father_id:
        father_list.append(i)

    digui(project_id, father_list)
    return JsonResponse({'status': True})


# 删除函数
def digui(project_id, father_list):
    the_father = father_list
    for i in the_father:  # 循环追加子类信息 到the_father
        son = S28().search('file_repository', {'father': i[0]})  # 子目录查讯
        print(son)
        for j in son:  # () ,()
            the_father.append(j)
    for i in the_father:  # 循环删除the_father的信息
        if i[3] == '2':  # 如果删除的是文件  那么就要减去项目已经占用的大小
            add_space = S28().search('file_repository', {'id': str(i[0])})
            space = S28().search('project', {'id': project_id})
            if space[0][7] == None:
                delete_file('{}-1302094470'.format(project_id), i[7])
            else:
                delete_file('{}-1302094470'.format(project_id), i[7])
                S28().upload('project', {'use_space': str(space[0][7]-add_space[0][4])}, {'id': str(project_id)})

        S28().delete_use('file_repository', {'id': i[0]})


@csrf_exempt
def cos_credentials(request, project_id):
    """获取cos上传临时凭证"""
    print('----------------------------------------- 上传文件正在执行 -------------------------------')
    info = json.loads(request.body.decode('utf-8'))
    space = 0
    for i in info:
        space +=i['size']
    # 查询当前用户用了多少空间
    user_space = S28().py_searche('select sum(use_space) from project where creator_id="{}"'.format(request.user_id))
    if user_space[0][0] == None:
        sum_space = space
    else:
        sum_space = space + int(user_space[0][0])  #request.space_num
    if sum_space > int(request.space_num):
        return JsonResponse({'status': False, 'error': '容量不够 请升级套餐'})
    else:
        # 上传临时凭证
        bucket = '{}-1302094470'.format(request.obj[0][0])
        data = cos_credentialss(bucket, 'ap-beijing')
        # 并且给数据库的用户容量修改为 sum_space
        return JsonResponse({'status': True, 'data': data})


@csrf_exempt
def file_post(request, project_id):
    """已上传的成功的文件写入数据库"""
    print('------------------------- 收到了要存放数据库中的数据 ---------------------------')

    file_name = request.POST.get('name')
    file_size = request.POST.get('size')
    file_father = request.POST.get('father')
    file_key = request.POST.get('location')
    file_thekey = request.POST.get('key')
    print(file_name, type(file_name))
    print(file_size, type(file_size))
    print(file_father, type(file_father))
    print(file_key, type(file_key))
    print(project_id, type(project_id))
    S28().insert_into('file_repository',
                      {'name': str(file_name),
                       'type': '2', 'father': str(file_father),
                       'project_id': str(project_id),
                       'space': str(file_size),
                       'name_key': str(file_key),
                       'keyadd': str(file_thekey)
                       })
    res = S28().search('file_repository', {'name_key': file_key})
    # 把这个文件的大小存放到这个项目的use_space字段
    ret = int(S28().py_searche('select sum(space) from file_repository where project_id="{}"'.format(project_id))[0][0])
    S28().upload('project', {'use_space':ret}, {'id':request.obj[0][0]})
    result = {
        'id': res[0][0],
        'name': res[0][2],
        'space': res[0][4],
        'url': reverse('file_download', kwargs={'project_id': project_id, 'file_id': res[0][0]})
    }
    print("---------------------------------------------- 文件上传成功 ---------------------------------------")
    return JsonResponse({'status': True, 'data': result})
import requests

@csrf_exempt
def file_download(request, project_id, file_id):
    # 判断当前用户是否拥有这个项目
    print('_---------------------------------------------- 下载请求到来 ---------------------------------------')
    # bucket = '{}-1302094470'.format(request.obj[0][0])
    # data = cos_credentialss(bucket, 'ap-beijing')
    # # 并且给数据库的用户容量修改为 sum_space
    # return JsonResponse({'status': True, 'data': data})

    #  返回文件内容
    file_tuple = S28().search('file_repository', {'id': file_id, 'project_id': project_id})
    res = requests.get('http://{}'.format(file_tuple[0][6]))
    data = res.iter_content()
    response = HttpResponse(data, content_type="application/octet-stream")
    from django.utils.encoding import escape_uri_path
    # 设置响应头
    response['Content-Disposition'] = 'attachment; filename={}'.format((escape_uri_path(file_tuple[0][2])))
    return response